#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H

#include <QObject>
#include <QList>

class QSqlDatabase;
class AbstractStorage;
class AbstractContainer;
class TableInfo;
class QIODevice;
class QXmlStreamWriter;
class DataTreeHelper;

class DatabaseManager : public QObject
{
    Q_OBJECT

public:
    static DatabaseManager* instance();
    ~DatabaseManager();

    bool initDatabases(AbstractContainer *databases);
    bool initDatabase(AbstractStorage *database);
    bool updateTables(QIODevice *source, QSqlDatabase &db, const QString &deleteFilter = QString());

    static bool tableToXml(QXmlStreamWriter *pXml, DataTreeHelper *dtHelper);
    static bool dataTreeToXml(QXmlStreamWriter *pXml, DataTreeHelper *dtHelper, const QString filterField = QString("id") );

private:
    bool initTable(AbstractStorage *table, const QString &dbName);
    bool initTable(AbstractStorage *table, QSqlDatabase &db);
    bool createTable(AbstractStorage *table, QSqlDatabase &db);
    void updateTableStruct(AbstractStorage *table, TableInfo* oldStruct, QSqlDatabase &db);

    inline bool renameTable(const QString &origName, const QString &newName, QSqlDatabase &db);
    inline bool copyTableData(const QString &srcTable, const QString &destTable, QSqlDatabase &db, const QStringList &columns);
    inline bool dropTable(const QString &tableName, QSqlDatabase &db);

    bool isTableExist(const QString &tableName, const QSqlDatabase &db);

    static bool childsToXml(QXmlStreamWriter *pXml, DataTreeHelper *dtHelper, QString id);
private:
    QList<QSqlDatabase*> m_databases;
    AbstractContainer *m_databasesContainer;

    static DatabaseManager *m_DatabaseManager;
    DatabaseManager(); // Singleton
};

#endif // DATABASEMANAGER_H
